import { Component, OnInit, Injector, ViewChild } from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { Table } from 'primeng/table';
import { Paginator, LazyLoadEvent } from 'primeng/primeng';
import { PrimengTableHelper } from '@shared/helpers/PrimengTableHelper';
import {
    ListDtoExtensionsItem,
    GetStock_AuditInputDto,
    StockZT_LostBillItemServiceProxy,
    Stock_LostToolItemListDto,
    StockZT_AuditServiceProxy,
    Stock_LostToolBaseListDto,
    ComboboxItemDto,
    SessionServiceProxy
} from '@shared/service-proxies/stock-service-proxies';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';
import { UserDataPermissionServiceProxy } from '@shared/service-proxies/stock-service-proxies';
import { AppConsts } from '@shared/AppConsts';
import { CreateToolLostOpinionModalComponent } from './create-or-edit-tool-lost-opinion-modal.component';

@Component({
    templateUrl: './tool-lost-index.component.html',
    animations: [appModuleAnimation()],
    selector: 'toollost'
})
export class ToolLostIndexComponent extends AppComponentBase {
    @ViewChild('dataTable') dataTable: Table;
    @ViewChild('paginator') paginator: Paginator;

    @ViewChild('detailDataTable') detailDataTable: Table;
    @ViewChild('detailPaginator') detailPaginator: Paginator;

    @ViewChild('createToolLostOpinionModalComponent') createOpinionModalComponent: CreateToolLostOpinionModalComponent;

    // filters
    deptFilter = '';
    taskNumFilter = '';
    drawingNumFilter = '';
    materialCodeFilter = '';
    certificationNumFilter = '';
    reCheckFilter = '';
    supplierFilter = '';
    warehouseNameFilter = '';
    billcode = '';

    userDataPermissions;
    selectedDepts;
    extensions: Array<ListDtoExtensionsItem>;
    detialExtensions: Array<ListDtoExtensionsItem>;

    detailPrimengTableHelper: PrimengTableHelper;
    selectedBill: Stock_LostToolBaseListDto;
    auditDto: GetStock_AuditInputDto;
    billStatusOptions = [
        { label: '全部', value: undefined },
        { label: '新建', value: '新建' },
        { label: '已提交', value: '已提交' },
        { label: '已出库', value: '已出库' }
    ];
    billstatus = '';
    selectedBillItem = new Stock_LostToolItemListDto();

    constructor(
        injector: Injector,
        private _billService: StockZT_LostBillItemServiceProxy,
        private _userDataPermissionServiceProxy: UserDataPermissionServiceProxy,
        private _auditService: StockZT_AuditServiceProxy,
        private _base_SessionServiceProxy: SessionServiceProxy
    ) {
        super(injector);
        this.detailPrimengTableHelper = new PrimengTableHelper();
    }

    ngOnInit(): void {
        this._userDataPermissionServiceProxy.getUserDataPermissions('Base_Bill').subscribe(result => {
            this.userDataPermissions = result.items.map(e => {
                return {
                    label: e.displayText,
                    value: e
                };
            });

            this._base_SessionServiceProxy.getCurrentDept().subscribe(result => {
                let ssData = new ComboboxItemDto();
                ssData.value = result.value;
                ssData.isSelected = false;
                ssData.displayText = result.label;
                let ss: ComboboxItemDto[] = [ssData];
                this.selectedDepts = ss;
                this.getBills();
            });

        });
    }

    getBills(event?: LazyLoadEvent, resetpage?: boolean) {
        if (!this.selectedDepts) {
            return;
        }
        if (this.primengTableHelper.shouldResetPaging(event) || event.first == undefined) {
            if (resetpage == undefined) {
                this.paginator.changePage(0);
                return;
            }
        }

        this.primengTableHelper.showLoadingIndicator();

        this._billService
            .getLostToolBaseListExtension(
                undefined,
                this.selectedDepts,
                this.materialCodeFilter,
                this.billcode,
                this.billstatus,
                '',
                undefined,
                undefined,
                undefined,
                this.primengTableHelper.getSorting(this.dataTable),
                this.primengTableHelper.getMaxResultCount(this.paginator, event),
                this.primengTableHelper.getSkipCount(this.paginator, event)
            )
            .subscribe(result => {
                this.extensions = result.items;
                this.primengTableHelper.totalRecordsCount = result.stock_LostToolBaseList.totalCount;
                this.primengTableHelper.records = result.stock_LostToolBaseList.items;
                this.primengTableHelper.hideLoadingIndicator();
                this.detailPrimengTableHelper.totalRecordsCount = 0;
                this.detailPrimengTableHelper.records = null;
                this.selectedBill = null;
                this.selectedBillItem = null;
            });
    }
    submitBill() {
        if (this.selectedBill.f_BillStatus != '新建') {
            this.message.warn('已提交或已审核！');
            return;
        }
        if (!this.selectedBill) {
            return;
        }
        if (this.detailPrimengTableHelper.totalRecordsCount <= 0) {
            this.message.warn('没有添加明细，不能提交');
            return;
        }
        this.auditDto = new GetStock_AuditInputDto();
        this.auditDto.id = this.selectedBill.id;
        this.message.confirm('确认提交？', isConfirmed => {
            if (isConfirmed) {
                this._billService
                    .submitToolLostBillBase(this.selectedBill.id)
                    .pipe(
                        finalize(() => {
                            this.primengTableHelper.hideLoadingIndicator();
                        })
                    )
                    .subscribe(() => {
                        this._billService.submitToolAuditBill(this.auditDto).pipe(
                            finalize(() => {
                                this.primengTableHelper.hideLoadingIndicator();
                            })
                        ).subscribe(() => {
                            this.notify.success(this.l('提交成功'));
                            this.getLostToolBase();
                            this.selectedBill.f_BillStatus = "已提交";
                            this.primengTableHelper.hideLoadingIndicator();
                        });
                    });
            }
        });
    }
    postBill() {
        if (!this.selectedBill) {
            return;
        }
        this.message.confirm('确认过账该条数据吗？', isConfirmed => {
            if (isConfirmed) {
                this.primengTableHelper.showLoadingIndicator();
                this._billService
                    .postToolLostBillBase(this.selectedBill.id)
                    .pipe(
                        finalize(() => {
                            this.primengTableHelper.hideLoadingIndicator();
                        })
                    )
                    .subscribe(() => {
                        this.notify.success(this.l('更新成功'));
                        this.getLostToolBase();
                        this.selectedBill.f_BillStatus = "已出库";
                        this.selectedBill.f_Posted = "已过账";
                        this.primengTableHelper.hideLoadingIndicator();
                    });
            }
        });
    }
    sendBackBill() {
        if (this.selectedBill.f_BillStatus == '已审核') {
            this.message.warn('已审核，不能退回！');
            return;
        }
        if (this.selectedBill.f_Posted == '已过帐') {
            this.message.warn('已过账，不能退回！');
            return;
        }
        if (!this.selectedBill) {
            return;
        }

        // this.message.confirm('确认退回该条数据吗？', isConfirmed => {
        //     if (isConfirmed) {
        //this.primengTableHelper.showLoadingIndicator();
        this.auditDto = new GetStock_AuditInputDto();
        this.auditDto.id = this.selectedBill.id;
        this.createOpinionModalComponent.show(this.selectedBill, '1');
        // this._billService
        //     .sendBackToolOutBillBase(this.selectedBill.id)
        //     .pipe(
        //         finalize(() => {

        //            // this.primengTableHelper.hideLoadingIndicator();
        //         })
        //     )
        //     .subscribe(() => {
        //        // this.notify.success(this.l('更新成功'));
        //         //this.getBills();
        //         //this.primengTableHelper.hideLoadingIndicator();
        //     });
        // //     }
        // // });
    }

    printBill() {
        if (this.selectedBill === null || this.selectedBill.id === undefined) {
            this.notify.error('请选择需要打印的单据！');
        } else {
            //装配类派工单
            window.open(
                AppConsts.printAddr + '/webroot/decision/view/report?viewlet=erp/XHWZCKD.cpt&BillId=' +
                this.selectedBill.id
            );
        }
    }

    printBillList() {
        if (this.selectedBill === null || this.selectedBill.id === undefined) {
            this.notify.error('请选择需要打印的单据！');
        } else {
            //装配类派工单
            window.open(
                AppConsts.printAddr + '/webroot/decision/view/report?viewlet=erp/XHWZCKDHZ.cpt&BillId=' +
                this.selectedBill.id
            );
        }
    }
    reloadData(event) {
        if (event == null || event == undefined) {
            this.getBills();
        } else {
            this.getBillItems();
        }
    }
    getBillItems(event?: LazyLoadEvent) {
        if (!this.selectedBill) {
            return;
        }
        if (this.detailPrimengTableHelper.shouldResetPaging(event)) {
            this.detailPaginator.changePage(0);

            return;
        }

        this.primengTableHelper.showLoadingIndicator();

        this._billService
            .getLostToolItemListExtension(
                this.selectedBill.id,
                this.detailPrimengTableHelper.getSorting(this.detailDataTable),
                this.detailPrimengTableHelper.getMaxResultCount(this.detailPaginator, event),
                this.detailPrimengTableHelper.getSkipCount(this.detailPaginator, event)
            )
            .subscribe(result => {
                this.detialExtensions = result.items;
                this.detailPrimengTableHelper.totalRecordsCount = result.stock_LostToolItemList.totalCount;
                this.detailPrimengTableHelper.records = result.stock_LostToolItemList.items;
                this.primengTableHelper.hideLoadingIndicator();

                this.selectedBillItem = null;
            });
    }

    deleteBill() {
        if (!this.selectedBill) {
            return;
        }

        this.message.confirm('确认删除该条数据吗？', isConfirmed => {
            if (isConfirmed) {
                this.primengTableHelper.showLoadingIndicator();
                this._billService
                    .deleteLostBillBase(this.selectedBill.id)
                    .pipe(
                        finalize(() => {
                            this.primengTableHelper.hideLoadingIndicator();
                        })
                    )
                    .subscribe(() => {
                        this.notify.success(this.l('SuccessfullyDeleted'));
                        this.getBills();
                        this.primengTableHelper.hideLoadingIndicator();
                    });
            }
        });
    }

    deleteBillItem() {
        if (!this.selectedBillItem) {
            return;
        }

        this.message.confirm('确认删除该条数据吗？', isConfirmed => {
            if (isConfirmed) {
                this.primengTableHelper.showLoadingIndicator();
                this._billService
                    .deleteLostBillItem(this.selectedBillItem.id)
                    .pipe(
                        finalize(() => {
                            this.primengTableHelper.hideLoadingIndicator();
                        })
                    )
                    .subscribe(() => {
                        this.notify.success(this.l('SuccessfullyDeleted'));
                        this.getBillItems();
                        this.primengTableHelper.hideLoadingIndicator();
                    });
            }
        });
    }

    //提交/审核
    auditBill() {
        if (this.selectedBill.f_BillStatus != '已提交') {
            this.message.warn('未提交或已审核完毕！');
            return;
        }
        if (!this.selectedBill) {
            return;
        }
        this._auditService.isCurrentNodeUser(this.selectedBill.f_WorkflowId).subscribe(result => {
            if (result == false) {
                this.message.warn('审核人不符，无法审批！');
            } else {
                this.auditDto = new GetStock_AuditInputDto();
                this.auditDto.id = this.selectedBill.id;
                this.createOpinionModalComponent.show(this.selectedBill, '0');
            }
        });

    }
    //提交审核过账后，获取单据对应改变的信息（页面不刷新）
    getLostToolBase() {
        if (this.selectedBill == null || this.selectedBill.id == undefined)
            return;

        this.primengTableHelper.showLoadingIndicator();
        this._billService.getLostToolBaseById(this.selectedBill.id)
            .subscribe(result => {
                this.selectedBill.f_BillStatus = result.f_BillStatus;
                this.selectedBill.f_Posted = result.f_Posted;
                this.selectedBill.f_NodeUser = result.f_NodeUser;
                this.selectedBill.f_WorkflowId = result.f_WorkflowId;

                this.primengTableHelper.hideLoadingIndicator();
            })
    }
}
